import { userFunctionMap } from '@/consts/maintaincheckorder.consts';
import { maintainadmin, norole, nologin, maintainer } from '@/consts/roles.consts';
/**
 *
 * @param {string} action 操作对应的key,请使用repairactions 常量
 * @param {object} order 对应的工单
 * @param {object} userinfo 用户信息对象包含 username roles phone
 * @param {string} queryphone 如果使用报修查询里手机号查询，需要传入
 * @returns
 */
export const examRpairOrderAction = (action, order, userinfo, queryphone) => {
    if (!order) {
        return false;
    }
    const { status } = order;
    const { username, roles } = userinfo;
    const phone = queryphone || userinfo.phone;
    const owner = username === order.administrator;
    const selfphone = phone === order.phone;
    const creator = username === order.creator;
    const other = !owner;
    const validate_map = { owner, selfphone, creator, other };

    let role;
    if (roles === undefined) {
        role = nologin;
    } else if (roles.includes(maintainadmin)) {
        role = maintainadmin;
    } else if (roles.includes(maintainer)) {
        role = maintainer;
    } else {
        role = norole;
    }

    const result = userFunctionMap[status] &&
                    userFunctionMap[status][role] &&
                    userFunctionMap[status][role][action];
    if (!result) {
        return false;
    }
    if (Array.isArray(result)) {
        const operator = result[0];
        result.splice(0, 1);

        if (operator === 'or') {
            return result.some((child) => {
                return validate_map[child];
            });
        } else if (operator === '&') {
            return result.every((child) => {
                return validate_map[child];
            });
        }
    }
    if (typeof result === 'string') {
        return validate_map[result];
    }

    return result;
};
